#pragma once 
#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>

class UdpClinet
{
  private:
    int sockfd;
    std::string server_ip;
    int server_port;
  public:
    UdpClinet(std::string _ip,int _port):server_ip(_ip),server_port(_port)
    {
    }
    ~UdpClinet()
    {
      if(sockfd>=0)
        close(sockfd);
    }
    bool InitUdpClinet()
    {
      sockfd=socket(AF_INET,SOCK_DGRAM,0);
      if(sockfd<0)
      {
        std::cerr<<"sockfd 错误"<<std::endl;
        return false;
      }
    std::cout<<"socket 成功"<<std::endl;
      return true;
    }
    void start()
    {
      struct sockaddr_in peer;
      memset(&peer,0,sizeof(peer));
      peer.sin_family=AF_INET;
      peer.sin_addr.s_addr=inet_addr(server_ip.c_str());
      peer.sin_port=htons(server_port);

      socklen_t len=sizeof(peer);
      std::string msg;
      for(;;)
      {
        std::cout<<"请输入：";
        std::cin>>msg;
        int size=sendto(sockfd,msg.c_str(),msg.size(),0,(struct sockaddr*)&peer,len);

        char buffer[128];
        struct sockaddr_in tmp;
        socklen_t temp=sizeof(tmp);
         int size1=recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&tmp,&temp);
        if(size<0)
        {
          std::cout<<"recvfrom 错误"<<std::endl;
          continue;
        }

        buffer[size1]=0;
        std::cout<<buffer<<std::endl;
      }
    }
};
